﻿using System;
using System.Linq;
using System.Web.Mvc;
using Diploma.Models;
using Diploma.Validation;
using System.Collections.Generic;
using DiplomaWeb.Models;
using DiplomaWeb.Models.Reviewer;
using DiplomaWeb.Properties;

namespace DiplomaWeb.Controllers
{
    [Authorize]
    public class StudentsController : MasterController
    {
        public StudentsController(DataManager dataManager) : base(dataManager)
        {
        }

        [Authorize(Roles = "Administrator")]
        [HttpGet]
        public ActionResult Edit(Guid id)
        {
            Student student = DataManager.StudentsRepository.GetStudent(id);
            if (student == null)
                throw new Exception();
            ViewData.Model = student;
            ViewData["Levels"] = new SelectList(DataManager.QualificationLevelsRepository.GetAllLevels(),
                                                "QualificationLevelId", "Name",
                                                student.StudentsGroup.QualificationLevelId);
            ViewData["Groups"] =
                new SelectList(
                    DataManager.QualificationLevelsRepository.GetStudentGroups(student.StudentsGroup.QualificationLevel),
                    "StudentsGroupId", "Name", student.StudentsGroupId);

            return PartialView("~/Views/Administrators/Students/EditStudentControl.ascx");
        }

        [Authorize(Roles = "Administrator")]
        [HttpPost]
        public JsonResult Edit(Student student)
        {
            ValidationErrors = Validator.ValidateStudent(student);
            if (ValidationErrors.Count() == 0)
            {
                DataManager.StudentsRepository.Update(student);
            }

            return Json(ValidationErrors, "text/plain", JsonRequestBehavior.AllowGet);
        }

        [Authorize(Roles = "Administrator")]
        [HttpPost]
        public JsonResult Add(Student student)
        {
            ValidationErrors = Validator.ValidateStudent(student);
            if (ValidationErrors.Count() == 0)
            {
                DataManager.StudentsRepository.Add(student);
            }

            return Json(ValidationErrors, "text/plain", JsonRequestBehavior.AllowGet);
        }

        [Authorize(Roles = "Administrator")]
        [HttpGet]
        public ActionResult Add()
        {
            ViewData["Levels"] = new SelectList(DataManager.QualificationLevelsRepository.GetAllLevels(),
                                                "QualificationLevelId", "");

            return PartialView("~/Views/Administrators/Students/AddStudentControl.ascx");
        }

        [Authorize(Roles = "Administrator, SystemManager")]
        [HttpPost]
        public ActionResult Delete(Guid[] selectedStudents)
        {
            foreach (Guid studentId in selectedStudents)
            {
                Student student = DataManager.StudentsRepository.GetStudent(studentId);
                if (student == null)
                    throw new Exception();
                DataManager.StudentsRepository.Delete(student);
            }
            return new EmptyResult();
        }

        [HttpPost]
        public ActionResult Restore(Guid[] selectedStudents)
        {
            foreach (Guid studentId in selectedStudents)
            {
                DataManager.StudentsRepository.Restore(studentId);
            }

            return new ContentResult();
        }

        public ActionResult Lecturers()
        {
            ViewData.Model = DataManager.LecturersRepository.GetAllLecturers();

            return View();
        }

        [Authorize(Roles = "Student")]
        public ActionResult LecturersThemes(Guid lecturerId)
        {
            Lecturer lecturer = DataManager.LecturersRepository.GetLecturer(lecturerId);
            if (lecturer == null)
                return null;
            ViewData.Model = lecturer;
            ViewData["LoggedUser"] = LoggedUser;
            ViewData["FreeThemes"] = DataManager.LecturersRepository.GetFreeThemes((Student)LoggedUser);
            ViewData["CanTakingTheme"]= false;
            return View();
        }

        [Authorize(Roles = "Student")]
        public ActionResult Home()
        {
            var student = LoggedUser as Student;
            if (student == null)
                throw new Exception();
            ViewData["LoggedUser"] = LoggedUser;
            if (student.IsAssigned)
            {
                ViewData.Model = student.CollaborationRoom;
                return View("CollaborationRoom");
            }
            else
            {
                CollaborationPropose prop = DataManager.StudentsRepository.GetCollaborationPropose(student);
                if (prop != null)
                {
                    ViewData.Model = prop;
                    return View("PendingTheme");
                }
                else
                {
                    ViewData.Model = DataManager.LecturersRepository.GetFreeThemes(student);
                    return View("FreeThemes");
                }
            }
        }

        public ActionResult News()
        {
            return View();
        }


        [Authorize(Roles = "Student")]
        public ActionResult Propose(Guid id)
        {
            CollaborationRoom roomViewMode = DataManager.CollaborationRoomRepository.GetCollaborationRoom(id);
            if (roomViewMode == null)
                throw new Exception();
            ViewData.Model = roomViewMode;

            return View();
        }


        [Authorize(Roles = "Student")]
        [HttpPost]
        public ActionResult Propose(CollaborationRoom proposeRoomViewMode)
        {
            CollaborationRoom roomViewMode =
                DataManager.CollaborationRoomRepository.GetCollaborationRoom(proposeRoomViewMode.CollaborationRoomId);
            if (roomViewMode == null)
                throw new Exception();
            DataManager.CollaborationRoomRepository.Participate(roomViewMode, LoggedUser as Student, proposeRoomViewMode.BaseTheme,
                                                                proposeRoomViewMode.BaseDescription);

            return RedirectToRoute("Default", new {controller = "Students", action = "Home"});
        }

        [Authorize(Roles = "Student")]
        public ActionResult ParticipateRoom(Guid id)
        {
            var student = LoggedUser as Student;
            CollaborationRoom roomViewMode = DataManager.CollaborationRoomRepository.GetCollaborationRoom(id);
            DataManager.CollaborationRoomRepository.Participate(roomViewMode, student);

            return RedirectToRoute("Default", new {controller = "Students", action = "Home"});
        }

        public ActionResult Group(Guid id)
        {
            StudentsGroup group = DataManager.StudentsGroupsRepository.GetStudentsGroup(id);
            if (group == null)
                throw new Exception();

            ViewData["DefaultAction"] = "Delete";
            return PartialView("~/Views/Students/ViewStudensListControl.ascx",
                               DataManager.StudentsRepository.GetStudentsGrouped(group));
        }

        public ActionResult GetDeleted()
        {
            ViewData.Model = DataManager.StudentsRepository.GetDeletedStudentsGroupedByGroupAndLevel();
            ViewData["DefaultAction"] = "Restore";
            return PartialView("~/Views/Students/ViewStudensListControl.ascx");
        }

        public ActionResult StudentsTasks(Guid studentId, Guid globalTaskId)
        {
            GlobalTask globalTask = DataManager.GlobalTasksRepository.GetGlobalTask(globalTaskId);
            Student student = DataManager.StudentsRepository.GetStudent(studentId);
            if (globalTask == null || student == null)
                throw new Exception();
            IEnumerable<Task> model = student.CollaborationRoom == null
                                          ? null
                                          : globalTask.Tasks.Where(
                                              gt =>
                                              gt.CollaborationRoomId == student.CollaborationRoom.CollaborationRoomId &&
                                              gt.DeletionDate == null).OrderBy(t => t.StartDate);

            return PartialView("~/Views/Planings/TasksListControl.ascx", model);
        }

        public PartialViewResult StudentProperties(Guid studentId)
        {
            var viewData = new StudentProgressViewModel();
            viewData.ToViewModel(DataManager.StudentsRepository.GetStudent(studentId));
            return PartialView(viewData);
        }

        #region Change Password

        [Authorize(Roles = "Student")]
        public ActionResult ChangePassword()
        {
            return View("~/Views/ChangePassword.aspx", new ChangePasswordViewModel());
        }

        [HttpPost]
        [Authorize(Roles = "Student")]
        public ActionResult ChangePassword(ChangePasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var student = LoggedUser as Student;
                if (student == null)
                    throw new Exception("User is not student");

                if (String.Equals(student.Password, model.OldPassword, StringComparison.CurrentCulture))
                {
                    DataManager.UsersRepository.UpdatePassword(student.UserId, model.NewPasswordFirst);
                    model.IsSaved = true;
                    return View("~/Views/ChangePassword.aspx", new ChangePasswordViewModel { IsSaved = true });
                }

                ModelState.AddModelError(String.Empty, ErrorMessages.msg_LecturersController_IncorrectOldPassword);
                return View("~/Views/ChangePassword.aspx", new ChangePasswordViewModel());
            }

            return View("~/Views/ChangePassword.aspx", new ChangePasswordViewModel());
        }

        #endregion
    }
}